package org.proddevplm.servlets;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.proddevplm.constants.ControllerConstants;
import org.proddevplm.constants.UserConstants;
import org.proddevplm.dao.api.IResourceMgmt;
import org.proddevplm.dao.core.ResourceMgmt;
import org.proddevplm.dao.data.Resource;
import org.proddevplm.dao.data.User;
import org.proddevplm.dao.util.HibernateUtil;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Date;
import java.util.Iterator;
import java.util.List;


public class UploadServlet extends HttpServlet {

    private boolean isMultipart;
    private String filePath;
    private int maxFileSize = 8 * 1024 * 1024;
    private int maxMemSize = 4 * 1024;
    private File file;

    private IResourceMgmt resourceMgmt;
    private static final int BUFSIZE = 4 * 1024;

    public void init() {
        // Get the file location where it would be stored.
        filePath = ".//..//uploads//";


    }

    public void doPost(HttpServletRequest request,
                       HttpServletResponse response)
            throws ServletException, java.io.IOException {


        int productId = (Integer) request.getSession().getAttribute("productId");
        resourceMgmt = new ResourceMgmt();

        // Check that we have a file upload request
        isMultipart = ServletFileUpload.isMultipartContent(request);

        DiskFileItemFactory factory = new DiskFileItemFactory();
        // maximum size that will be stored in memory
        factory.setSizeThreshold(maxMemSize);
        // Location to save data that is larger than maxMemSize.
        factory.setRepository(new File("./"));

        // Create a new file upload handler
        ServletFileUpload upload = new ServletFileUpload(factory);
        // maximum file size to be uploaded.
        upload.setSizeMax(maxFileSize);

        User user = (User) request.getSession().getAttribute(UserConstants.USER);

        try {
            // Parse the request to get file items.
            List fileItems = upload.parseRequest(request);

            // Process the uploaded file items
            Iterator i = fileItems.iterator();
            HibernateUtil.currentSession().beginTransaction();

            while (i.hasNext()) {
                FileItem fi = (FileItem) i.next();
                if (!fi.isFormField()) {
                    // Get the uploaded file parameters
                    String fieldName = fi.getFieldName();
                    String fileName = fi.getName();
                    String contentType = fi.getContentType();
                    boolean isInMemory = fi.isInMemory();
                    long sizeInBytes = fi.getSize();
                    String resFileName;


                    if (fileName.lastIndexOf("\\") >= 0) {
                        resFileName = fileName.substring(fileName.lastIndexOf("\\"));
                    } else {
                        resFileName = fileName.substring(fileName.lastIndexOf("\\") + 1);
                    }
                    System.out.println("RESFILENAME: " + resFileName);
                    String fileType = resFileName.substring(resFileName.lastIndexOf("."), resFileName.length());
                    System.out.println("File type: " + fileType);
                    Resource res = resourceMgmt.getResourceByNameandProductId(resFileName, productId);



                    file = new File(filePath + res.getVersion() + "_" + productId + "_" +
                            resFileName);
                }
                fi.write(file);
            }

        } catch (Exception ex) {
            ex.printStackTrace();
        }

        finally

        {
            
        }

        response.sendRedirect("/proddev/pages/index.jsp");
    }

    public void doGet(HttpServletRequest request,
                      HttpServletResponse response)
            throws ServletException, java.io.IOException {
        try {
            HibernateUtil.currentSession().beginTransaction();
            int productId = (Integer) request.getSession().getAttribute("productId");
            String resFileName = request.getParameter("fileName");
            Resource res = resourceMgmt.getResourceByNameandProductId(resFileName, productId);


            File f = new File(filePath + res.getVersion() + "_" + productId + "_" + resFileName);
            int length = 0;
            ServletOutputStream op = response.getOutputStream();
            ServletContext context = getServletConfig().getServletContext();
            String mimetype = context.getMimeType(resFileName);

            //  Set the response and go!

            response.setContentType((mimetype != null) ? mimetype : "application/octet-stream");
            response.setContentLength((int) f.length());
            response.setHeader("Content-Disposition", "attachment; filename=\"" + resFileName + "\"");

            //  Stream to the requester.

            byte[] bbuf = new byte[BUFSIZE];
            DataInputStream in = new DataInputStream(new FileInputStream(f));

            while ((in != null) && ((length = in.read(bbuf)) != -1)) {
                op.write(bbuf, 0, length);
            }

            in.close();
            op.flush();
            op.close();
            res.setLocked(true);
            User user = (User) request.getSession().getAttribute(UserConstants.USER);
            res.setModifier(user.getSurname() + " " + user.getName());
            HibernateUtil.currentSession().merge(res);

        } catch (Exception e) {

        } finally {
            HibernateUtil.currentSession().getTransaction().commit();
        }

    }

}
